package com.secondriver.url.filter.urlrealm.groovy

import com.secondriver.url.filter.urlrealm.URLBean;

import groovy.sql.*;

class URLSqlQuery {

	def conn;

	def dbConfig;

	def  URLSqlQuery(dbConfig){
		if(null == dbConfig || dbConfig.size() ==0){
			throw new IllegalArgumentException(URLSqlQuery.getClass().getName()+' constructor method parameter dbConfig must not null, this is database connection configuration for query.');
		}
		this.dbConfig=dbConfig;
	}

	def queryURLBean(String sql, params){
		this.openConn();

		if(null==this.conn){
			throw new NullPointerException('URLSqlQuery conn must not null, when you execute sql statment . Please use it before call this.openConn() , so execute this.conn.Method , last time call this.closeConn().');
		}

		List<URLBean> listURLBean=new ArrayList<URLBean>();
		def urlBeanProperties=[];
		URLBean.class.getMetaClass().properties.each { meta->
			def p=meta.name;
			if(p !='class'){
				urlBeanProperties<<p;
			}
		};

		def meta={ meta->
			def fields=[];
			(1..meta.columnCount).each { it->
				fields<<meta.getColumnName(it);
			}
			if(urlBeanProperties.sort() != fields.sort()){
				throw new Exception('Please check you sql select filed , must with URLBean properties one-to-one correspondence. The URLBean is ' +{
					it->
					return it.toString();
				}.call(urlBeanProperties));
			}
		}

		this.conn.eachRow(params, sql, meta, { row->
			def urlBean=new URLBean(row.toRowResult());
			listURLBean<<urlBean;
		})

		this.closeConn();
		return listURLBean;
	}
	private def openConn(){
		this.conn=Sql.newInstance(
				this.dbConfig.url,
				this.dbConfig.user,
				this.dbConfig.password,
				this.dbConfig.driver);
		return this;
	}

	private def closeConn(){
		this.conn?.close();
		return this;
	}
}